package com.juzipi.demo.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.juzipi.demo.pojo.User;
import com.juzipi.demo.service.UserService;
import com.juzipi.demo.tools.Result;
import com.juzipi.demo.utils.JWTUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;

@RestController
@RequestMapping("test")
public class TestController {


    @Autowired
    private UserService userService;


    @PostMapping("login")
    public Result login(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ){
        User loginUser = userService.loginByUser(username,password);
        if (StringUtils.checkValNull(loginUser)){
            return Result.fail(404,"登陆失败");
        }else if (StringUtils.checkValNull(loginUser.getPassword())){
            return Result.fail(403,"密码错误");
        }
        //设置荷载
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        //放入用户名
        linkedHashMap.put("username",loginUser.getUsername());
        //生成token
        String token = JWTUtils.getToken(linkedHashMap);

        System.out.println(token);
        return Result.success("登陆成功",token);
    }


    @PostMapping("logout")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return Result.success("退出成功");
    }



    @GetMapping("user")
    public Result getUser(){
        List<User> users = userService.queryAllUser();
        if (CollectionUtils.isEmpty(users)){
            return Result.fail(404);
        }
        return Result.success(users);
    }


    //这两个角色都可以访问
    @RequiresRoles(logical = Logical.OR,value = {"user","admin"})
    //不需要特定的权限
    @GetMapping("hello")
    public Result hello(){
        return Result.success("这两个角色都可以访问,不需要特定的权限,获取成功！！！！！！");
    }



    //这两个角色都可以访问
    @RequiresRoles(logical = Logical.OR,value = {"user","admin"})
    @GetMapping("hellos")
    @RequiresPermissions("manage")//拥有 manage 权限才能访问
    public Result hellos(){
        return Result.success("这两个角色中拥有 manage 权限才能访问,获取成功！！！！！！");
    }



    //只有admin角色可以访问
    @RequiresRoles(value = {"admin"})
    @GetMapping("hi")
    @RequiresPermissions("manage")//拥有 manage 权限才能访问
    public Result hi(){
        return Result.success("只有admin角色,拥有 manage 权限才能访问，获取成功！！！！！！");
    }


}
